<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="google-site-verification" content="Xk9YWz2-rBE9P5__qdWz3nUr4zb9bIDSdANHpezjB04"><meta name="baidu-site-verification" content="aifbHeRmzy"><meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"><meta name="description" content="Goals determine what you going to be!!"><meta name="keyword" content="hjb, csjiabin, csjiabin Blog, 黄佳滨的博客, huangjiabin, 黄佳滨, html, css, javascript, js, JavaScript, Node, node, nodejs, h5, html5, 小程序, vue"><title>JavaScript有用的代码片段和trick - CSjiabin的博客 | CSjiabin&#39;s Blog</title><link rel="canonical" href="https://csjiabin.github.io"><link rel="manifest" href="/hux/pwa/manifest.json"><link rel="shortcut icon" href="/hux/img/favicon.ico"><link rel="apple-touch-icon" href="/hux/img/apple-touch-icon.png"><link rel="stylesheet" href="/hux/css/bootstrap.min.css"><link rel="stylesheet" href="/hux/css/hux-blog.min.css"><link rel="stylesheet" href="/hux/css/highlight.css"><link rel="stylesheet" href="/hux/css/rocket.css"><link rel="stylesheet" href="/hux/css/signature.css"><link rel="stylesheet" href="/hux/css/toc.css"><link rel="stylesheet" type="text/css" href="https://c.mipcdn.com/static/v1/mip.css"><link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!--[if lt IE 9]><script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script><script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script><![endif]--><script>!function(e,t,o,c,i,d,a){e.DaoVoiceObject=i,e[i]=e[i]||function(){(e[i].q=e[i].q||[]).push(arguments)},e[i].l=1*new Date,d=t.createElement(o),a=t.getElementsByTagName(o)[0],d.async=1,d.src=c,d.charset="utf-8",a.parentNode.insertBefore(d,a)}(window,document,"script",("https:"==document.location.protocol?"https:":"http:")+"//widget.daovoice.io/widget/bdc5c12d.js","daovoice"),daovoice("init",{app_id:"bdc5c12d"}),daovoice("update")</script><script></script></head><body ontouchstart=""><style type="text/css">header.intro-header{background-image:url(/hux/img/home-bg.jpg)}#signature{background-image:url(/hux/img/signature/white.png)}</style><link rel="stylesheet" href="/hux/css/post-style.css"><header class="intro-header"><div id="signature"><div class="container"><div class="row"><div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"><div class="post-heading"><div class="tags"></div><h1>JavaScript有用的代码片段和trick</h1><h2 class="subheading"></h2> <span class="meta">Posted by CSjiabin on 2018-08-22</span></div></div></div></div></div></header><nav class="navbar navbar-default navbar-custom navbar-fixed-top"><div class="container-fluid"><div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle"> <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> <a class="navbar-brand" href="/hux/">CSjiabin&#39;s Blog</a></div><div id="huxblog_navbar"><div class="navbar-collapse"><ul class="nav navbar-nav navbar-right"><li> <a href="/hux/">Home</a></li><li> <a href="/hux/about/">About</a></li><li> <a href="/hux/archives/">Archives</a></li><li> <a href="/hux/tags/">Tags</a></li></ul></div></div></div></nav><script>var $body=document.body,$toggle=document.querySelector(".navbar-toggle"),$navbar=document.querySelector("#huxblog_navbar"),$collapse=document.querySelector(".navbar-collapse");function handleMagic(e){0<$navbar.className.indexOf("in")?($navbar.className=" ",setTimeout(function(){$navbar.className.indexOf("in")<0&&($collapse.style.height="0px")},400)):($collapse.style.height="auto",$navbar.className+=" in")}$toggle.addEventListener("click",handleMagic)</script><article><div class="container"><div class="row"><div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 post-container"><h4> <span id="浮点数取整">浮点数取整</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> x = <span class="number">123.4545</span>;</span><br><span class="line">x &gt;&gt; <span class="number">0</span>; <span class="comment">// 123</span></span><br><span class="line">~~x; <span class="comment">// 123</span></span><br><span class="line">x | <span class="number">0</span>; <span class="comment">// 123</span></span><br><span class="line"><span class="built_in">Math</span>.floor(x); <span class="comment">// 123</span></span><br></pre></td></tr></table></figure><blockquote><p>注意：前三种方法只适用于32个位整数，对于负数的处理上和 Math.floor是不同的。</p></blockquote><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.floor(<span class="number">-12.53</span>); <span class="comment">// -13</span></span><br><span class="line"><span class="number">-12.53</span> | <span class="number">0</span>; <span class="comment">// -12</span></span><br></pre></td></tr></table></figure><h4> <span id="生成6位数字验证码">生成6位数字验证码</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line">(<span class="string">'000000'</span> + <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() *  <span class="number">999999</span>)).slice(<span class="number">-6</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="built_in">Math</span>.random().toString().slice(<span class="number">-6</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三</span></span><br><span class="line"><span class="built_in">Math</span>.random().toFixed(<span class="number">6</span>).slice(<span class="number">-6</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法四</span></span><br><span class="line"><span class="string">''</span> + <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * <span class="number">999999</span>);</span><br></pre></td></tr></table></figure><h4> <span id="16进制颜色代码生成">16进制颜色代码生成</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="string">'#'</span>+(<span class="string">'00000'</span>+</span><br><span class="line">    (<span class="built_in">Math</span>.random()*<span class="number">0x1000000</span>&lt;&lt;<span class="number">0</span>).toString(<span class="number">16</span>)).slice(<span class="number">-6</span>);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure><h4> <span id="驼峰命名转下划线">驼峰命名转下划线</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'componentMapModelRegistry'</span>.match(<span class="regexp">/^[a-z][a-z0-9]+|[A-Z][a-z0-9]*/g</span>).join(<span class="string">'_'</span>).toLowerCase(); <span class="comment">// component_map_model_registry</span></span><br></pre></td></tr></table></figure><h4> <span id="url查询参数转json格式">url查询参数转json格式</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ES6</span></span><br><span class="line"><span class="keyword">const</span> query = <span class="function">(<span class="params">search = <span class="string">''</span></span>) =&gt;</span> (<span class="function">(<span class="params">querystring = <span class="string">''</span></span>) =&gt;</span> (<span class="function"><span class="params">q</span> =&gt;</span> (querystring.split(<span class="string">'&amp;'</span>).forEach(<span class="function"><span class="params">item</span> =&gt;</span> (<span class="function"><span class="params">kv</span> =&gt;</span> kv[<span class="number">0</span>] &amp;&amp; (q[kv[<span class="number">0</span>]] = kv[<span class="number">1</span>]))(item.split(<span class="string">'='</span>))), q))(&#123;&#125;))(search.split(<span class="string">'?'</span>)[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对应ES5实现</span></span><br><span class="line"><span class="keyword">var</span> query = <span class="function"><span class="keyword">function</span>(<span class="params">search</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (search === <span class="keyword">void</span> <span class="number">0</span>) &#123; search = <span class="string">''</span>; &#125;</span><br><span class="line">  <span class="keyword">return</span> (<span class="function"><span class="keyword">function</span>(<span class="params">querystring</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (querystring === <span class="keyword">void</span> <span class="number">0</span>) &#123; querystring = <span class="string">''</span>; &#125;</span><br><span class="line">    <span class="keyword">return</span> (<span class="function"><span class="keyword">function</span>(<span class="params">q</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> (querystring.split(<span class="string">'&amp;'</span>).forEach(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (<span class="function"><span class="keyword">function</span>(<span class="params">kv</span>) </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> kv[<span class="number">0</span>] &amp;&amp; (q[kv[<span class="number">0</span>]] = kv[<span class="number">1</span>]);</span><br><span class="line">        &#125;)(item.split(<span class="string">'='</span>));</span><br><span class="line">      &#125;), q);</span><br><span class="line">    &#125;)(&#123;&#125;);</span><br><span class="line">  &#125;)(search.split(<span class="string">'?'</span>)[<span class="number">1</span>]);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">query(<span class="string">'?key1=value1&amp;key2=value2'</span>); <span class="comment">// es6.html:14 &#123;key1: "value1", key2: "value2"&#125;</span></span><br></pre></td></tr></table></figure><h4> <span id="获取url参数">获取URL参数</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getQueryString</span>(<span class="params">key</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> reg = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">"(^|&amp;)"</span>+ key +<span class="string">"=([^&amp;]*)(&amp;|$)"</span>);</span><br><span class="line">  <span class="keyword">var</span> r = <span class="built_in">window</span>.location.search.substr(<span class="number">1</span>).match(reg);</span><br><span class="line">  <span class="keyword">if</span>(!!r)&#123;</span><br><span class="line">      <span class="keyword">return</span>  <span class="built_in">unescape</span>(r[<span class="number">2</span>]);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="n维数组展开成一维数组">n维数组展开成一维数组</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = [<span class="number">1</span>, [<span class="number">2</span>, <span class="number">3</span>], [<span class="string">'4'</span>, <span class="number">5</span>, [<span class="string">'6'</span>,<span class="number">7</span>,[<span class="number">8</span>]]], [<span class="number">9</span>], <span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法一</span></span><br><span class="line"><span class="comment">// 限制：数组项不能出现`,`，同时数组项全部变成了字符数字</span></span><br><span class="line">foo.toString().split(<span class="string">','</span>); <span class="comment">// ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="comment">// 转换后数组项全部变成数字了</span></span><br><span class="line"><span class="built_in">eval</span>(<span class="string">'['</span> + foo + <span class="string">']'</span>); <span class="comment">// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三，使用ES6展开操作符</span></span><br><span class="line"><span class="comment">// 写法太过麻烦，太过死板</span></span><br><span class="line">[<span class="number">1</span>, ...[<span class="number">2</span>, <span class="number">3</span>], ...[<span class="string">'4'</span>, <span class="number">5</span>, ...[<span class="string">'6'</span>,<span class="number">7</span>,...[<span class="number">8</span>]]], ...[<span class="number">9</span>], <span class="number">10</span>]; <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法四</span></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">`[<span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(foo).replace(<span class="regexp">/\[|]/g</span>, <span class="string">''</span>)&#125;</span>]`</span>); <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法五</span></span><br><span class="line"><span class="keyword">const</span> flatten = <span class="function">(<span class="params">ary</span>) =&gt;</span> ary.reduce(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a.concat(<span class="built_in">Array</span>.isArray(b) ? flatten(b) : b), []);</span><br><span class="line">flatten(foo); <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法六</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">flatten</span>(<span class="params">a</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Array</span>.isArray(a) ? [].concat(...a.map(flatten)) : a;</span><br><span class="line">&#125;</span><br><span class="line">flatten(foo); <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br></pre></td></tr></table></figure><blockquote><p>注：更多方法请参考《How to flatten nested array in JavaScript?》</p></blockquote><h4> <span id="日期格式化">日期格式化</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">format1</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> z = &#123;</span><br><span class="line">    y: x.getFullYear(),</span><br><span class="line">    M: x.getMonth() + <span class="number">1</span>,</span><br><span class="line">    d: x.getDate(),</span><br><span class="line">    h: x.getHours(),</span><br><span class="line">    m: x.getMinutes(),</span><br><span class="line">    s: x.getSeconds()</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> y.replace(<span class="regexp">/(y+|M+|d+|h+|m+|s+)/g</span>, <span class="function"><span class="keyword">function</span>(<span class="params">v</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> ((v.length &gt; <span class="number">1</span> ? <span class="string">"0"</span> : <span class="string">""</span>) + <span class="built_in">eval</span>(<span class="string">'z.'</span> + v.slice(<span class="number">-1</span>))).slice(-(v.length &gt; <span class="number">2</span> ? v.length : <span class="number">2</span>))</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">format1(<span class="keyword">new</span> <span class="built_in">Date</span>(), <span class="string">'yy-M-d h:m:s'</span>); <span class="comment">// 17-10-14 22:14:41</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="built_in">Date</span>.prototype.format = <span class="function"><span class="keyword">function</span> (<span class="params">fmt</span>) </span>&#123; </span><br><span class="line">  <span class="keyword">var</span> o = &#123;</span><br><span class="line">    <span class="string">"M+"</span>: <span class="keyword">this</span>.getMonth() + <span class="number">1</span>, <span class="comment">//月份 </span></span><br><span class="line">    <span class="string">"d+"</span>: <span class="keyword">this</span>.getDate(), <span class="comment">//日 </span></span><br><span class="line">    <span class="string">"h+"</span>: <span class="keyword">this</span>.getHours(), <span class="comment">//小时 </span></span><br><span class="line">    <span class="string">"m+"</span>: <span class="keyword">this</span>.getMinutes(), <span class="comment">//分 </span></span><br><span class="line">    <span class="string">"s+"</span>: <span class="keyword">this</span>.getSeconds(), <span class="comment">//秒 </span></span><br><span class="line">    <span class="string">"q+"</span>: <span class="built_in">Math</span>.floor((<span class="keyword">this</span>.getMonth() + <span class="number">3</span>) / <span class="number">3</span>), <span class="comment">//季度 </span></span><br><span class="line">    <span class="string">"S"</span>: <span class="keyword">this</span>.getMilliseconds() <span class="comment">//毫秒 </span></span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">if</span> (<span class="regexp">/(y+)/</span>.test(fmt))&#123;</span><br><span class="line">    fmt = fmt.replace(<span class="built_in">RegExp</span>.$<span class="number">1</span>, (<span class="keyword">this</span>.getFullYear() + <span class="string">""</span>).substr(<span class="number">4</span> - <span class="built_in">RegExp</span>.$<span class="number">1.</span>length));</span><br><span class="line">  &#125; </span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> k <span class="keyword">in</span> o)&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">"("</span> + k + <span class="string">")"</span>).test(fmt))&#123;</span><br><span class="line">      fmt = fmt.replace(<span class="built_in">RegExp</span>.$<span class="number">1</span>, (<span class="built_in">RegExp</span>.$<span class="number">1.</span>length == <span class="number">1</span>) ? (o[k]) : ((<span class="string">"00"</span> + o[k]).substr((<span class="string">""</span> + o[k]).length)));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;     </span><br><span class="line">  <span class="keyword">return</span> fmt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>().format(<span class="string">'yy-M-d h:m:s'</span>); <span class="comment">// 17-10-14 22:18:17</span></span><br></pre></td></tr></table></figure><h4> <span id="统计文字个数">统计文字个数</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">wordCount</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> pattern = <span class="regexp">/[a-zA-Z0-9_\u0392-\u03c9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g</span>;</span><br><span class="line">  <span class="keyword">var</span> m = data.match(pattern);</span><br><span class="line">  <span class="keyword">var</span> count = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">if</span>( m === <span class="literal">null</span> ) <span class="keyword">return</span> count;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; m.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (m[i].charCodeAt(<span class="number">0</span>) &gt;= <span class="number">0x4E00</span>) &#123;</span><br><span class="line">      count += m[i].length;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      count += <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> text = <span class="string">'贷款买房，也意味着你能给自己的资产加杠杆，能够撬动更多的钱，来孳生更多的财务性收入。'</span>;</span><br><span class="line">wordCount(text); <span class="comment">// 38</span></span><br></pre></td></tr></table></figure><h4> <span id="特殊字符转义">特殊字符转义</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">htmlspecialchars</span> (<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> str = str.toString().replace(<span class="regexp">/&amp;/g</span>, <span class="string">"&amp;amp;"</span>).replace(<span class="regexp">/&lt;/g</span>, <span class="string">"&amp;lt;"</span>).replace(<span class="regexp">/&gt;/g</span>, <span class="string">"&amp;gt;"</span>).replace(<span class="regexp">/"/g</span>, <span class="string">'&amp;quot;'</span>);</span><br><span class="line">  <span class="keyword">return</span> str;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">htmlspecialchars(<span class="string">'&amp;jfkds&lt;&gt;'</span>); <span class="comment">// "&amp;amp;jfkds&amp;lt;&amp;gt;"</span></span><br></pre></td></tr></table></figure><h4> <span id="动态插入js">动态插入js</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">injectScript</span>(<span class="params">src</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> s, t;</span><br><span class="line">    s = <span class="built_in">document</span>.createElement(<span class="string">'script'</span>);</span><br><span class="line">    s.type = <span class="string">'text/javascript'</span>;</span><br><span class="line">    s.async = <span class="literal">true</span>;</span><br><span class="line">    s.src = src;</span><br><span class="line">    t = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'script'</span>)[<span class="number">0</span>];</span><br><span class="line">    t.parentNode.insertBefore(s, t);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="格式化数量">格式化数量</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatNum</span> (<span class="params">num, n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> num == <span class="string">"number"</span>) &#123;</span><br><span class="line">    num = <span class="built_in">String</span>(num.toFixed(n || <span class="number">0</span>));</span><br><span class="line">    <span class="keyword">var</span> re = <span class="regexp">/(-?\d+)(\d&#123;3&#125;)/</span>;</span><br><span class="line">    <span class="keyword">while</span> (re.test(num)) num = num.replace(re, <span class="string">"$1,$2"</span>);</span><br><span class="line">    <span class="keyword">return</span> num;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> num;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">formatNum(<span class="number">2313123</span>, <span class="number">3</span>); <span class="comment">// "2,313,123.000"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="string">'2313123'</span>.replace(<span class="regexp">/\B(?=(\d&#123;3&#125;)+(?!\d))/g</span>, <span class="string">','</span>); <span class="comment">// "2,313,123"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatNum</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> str.split(<span class="string">''</span>).reverse().reduce(<span class="function">(<span class="params">prev, next, index</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> ((index % <span class="number">3</span>) ? next : (next + <span class="string">','</span>)) + prev</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">formatNum(<span class="string">'2313323'</span>); <span class="comment">// "2,313,323"</span></span><br></pre></td></tr></table></figure><h4> <span id="身份证验证">身份证验证</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">chechCHNCardId</span>(<span class="params">sNo</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="keyword">this</span>.regExpTest(sNo, /^[<span class="number">0</span><span class="number">-9</span>]&#123;<span class="number">17</span>&#125;[X0<span class="number">-9</span>]$/)) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  sNo = sNo.toString();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> a, b, c;</span><br><span class="line">  a = <span class="built_in">parseInt</span>(sNo.substr(<span class="number">0</span>, <span class="number">1</span>)) * <span class="number">7</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">1</span>, <span class="number">1</span>)) * <span class="number">9</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">2</span>, <span class="number">1</span>)) * <span class="number">10</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">3</span>, <span class="number">1</span>)) * <span class="number">5</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">4</span>, <span class="number">1</span>)) * <span class="number">8</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">5</span>, <span class="number">1</span>)) * <span class="number">4</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">6</span>, <span class="number">1</span>)) * <span class="number">2</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">7</span>, <span class="number">1</span>)) * <span class="number">1</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">8</span>, <span class="number">1</span>)) * <span class="number">6</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">9</span>, <span class="number">1</span>)) * <span class="number">3</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">10</span>, <span class="number">1</span>)) * <span class="number">7</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">11</span>, <span class="number">1</span>)) * <span class="number">9</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">12</span>, <span class="number">1</span>)) * <span class="number">10</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">13</span>, <span class="number">1</span>)) * <span class="number">5</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">14</span>, <span class="number">1</span>)) * <span class="number">8</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">15</span>, <span class="number">1</span>)) * <span class="number">4</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">16</span>, <span class="number">1</span>)) * <span class="number">2</span>;</span><br><span class="line">  b = a % <span class="number">11</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (b == <span class="number">2</span>) &#123;</span><br><span class="line">    c = sNo.substr(<span class="number">17</span>, <span class="number">1</span>).toUpperCase();</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    c = <span class="built_in">parseInt</span>(sNo.substr(<span class="number">17</span>, <span class="number">1</span>));</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">switch</span> (b) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="string">"X"</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">9</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">8</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">7</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">6</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">7</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">5</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">8</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">4</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">9</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">3</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">10</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="测试质数">测试质数</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isPrime</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> !(<span class="regexp">/^.?$|^(..+?)\1+$/</span>).test(<span class="string">'1'</span>.repeat(n))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="统计字符串中相同字符出现的次数">统计字符串中相同字符出现的次数</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = <span class="string">'abcdaabc'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> info = arr</span><br><span class="line">    .split(<span class="string">''</span>)</span><br><span class="line">    .reduce(<span class="function">(<span class="params">p, k</span>) =&gt;</span> (p[k]++ || (p[k] = <span class="number">1</span>), p), &#123;&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(info); <span class="comment">//&#123; a: 3, b: 2, c: 2, d: 1 &#125;</span></span><br></pre></td></tr></table></figure><h4> <span id="使用void-0来解决undefined被污染问题">使用<code>void 0</code>来解决<code>undefined</code>被污染问题</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">undefined</span> = <span class="number">1</span>;</span><br><span class="line">!!<span class="literal">undefined</span>; <span class="comment">// true</span></span><br><span class="line">!!<span class="keyword">void</span>(<span class="number">0</span>); <span class="comment">// false</span></span><br></pre></td></tr></table></figure><h4> <span id="单行写一个评级组件">单行写一个评级组件</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"★★★★★☆☆☆☆☆"</span>.slice(<span class="number">5</span> - rate, <span class="number">10</span> - rate);</span><br></pre></td></tr></table></figure><h4> <span id="javascript-错误处理的方式的正确姿势">JavaScript 错误处理的方式的正确姿势</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    something</span><br><span class="line">&#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">    <span class="built_in">window</span>.location.href =</span><br><span class="line">        <span class="string">"http://stackoverflow.com/search?q=[js]+"</span> +</span><br><span class="line">        e.message;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="匿名函数自执行写法">匿名函数自执行写法</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">( <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;() );</span><br><span class="line">( <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125; )();</span><br><span class="line">[ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;() ];</span><br><span class="line"></span><br><span class="line">~ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line">! <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line">+ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line">- <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"></span><br><span class="line"><span class="keyword">delete</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">typeof</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">void</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">new</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">new</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> f = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"></span><br><span class="line"><span class="number">1</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="number">1</span> ^ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="number">1</span> &gt; <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br></pre></td></tr></table></figure><h4> <span id="两个整数交换数值">两个整数交换数值</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">20</span>, b = <span class="number">30</span>;</span><br><span class="line">a ^= b;</span><br><span class="line">b ^= a;</span><br><span class="line">a ^= b;</span><br><span class="line"></span><br><span class="line">a; <span class="comment">// 30</span></span><br><span class="line">b; <span class="comment">// 20</span></span><br></pre></td></tr></table></figure><h4> <span id="数字字符转数字">数字字符转数字</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">'1'</span>;</span><br><span class="line">+a; <span class="comment">// 1</span></span><br></pre></td></tr></table></figure><h4> <span id="最短的代码实现数组去重">最短的代码实现数组去重</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[...new <span class="built_in">Set</span>([<span class="number">1</span>, <span class="string">"1"</span>, <span class="number">2</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">3</span>])]; <span class="comment">// [1, "1", 2, 3]</span></span><br></pre></td></tr></table></figure><h4> <span id="用最短的代码实现一个长度为m6且值都n8的数组">用最短的代码实现一个长度为m(6)且值都n(8)的数组</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>(<span class="number">6</span>).fill(<span class="number">8</span>); <span class="comment">// [8, 8, 8, 8, 8, 8]</span></span><br></pre></td></tr></table></figure><h4> <span id="将argruments对象转换成数组">将argruments对象转换成数组</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> argArray = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// ES6：</span></span><br><span class="line"><span class="keyword">var</span> argArray = <span class="built_in">Array</span>.from(<span class="built_in">arguments</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// or</span></span><br><span class="line"><span class="keyword">var</span> argArray = [...arguments];</span><br></pre></td></tr></table></figure><h4> <span id="获取日期时间缀">获取日期时间缀</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取指定时间的时间缀</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>().getTime();</span><br><span class="line">(<span class="keyword">new</span> <span class="built_in">Date</span>()).getTime();</span><br><span class="line">(<span class="keyword">new</span> <span class="built_in">Date</span>).getTime();</span><br><span class="line"><span class="comment">// 获取当前的时间缀</span></span><br><span class="line"><span class="built_in">Date</span>.now();</span><br><span class="line"><span class="comment">// 日期显示转换为数字</span></span><br><span class="line">+<span class="keyword">new</span> <span class="built_in">Date</span>();</span><br></pre></td></tr></table></figure><h4> <span id="使用~xindexofy来简化xindexofy-gt-">使用<code>~x.indexOf('y')</code>来简化<code>x.indexOf('y') &gt; -</code></span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'hello world'</span>;</span><br><span class="line"><span class="keyword">if</span> (str.indexOf(<span class="string">'lo'</span>) &gt; <span class="number">-1</span>) &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (~str.indexOf(<span class="string">'lo'</span>)) &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="parseint-or-number"><code>parseInt()</code> or <code>Number()</code></span></h4><p>两者的差别之处在于<strong>解析</strong>和<strong>转换</strong>两者之间的理解。</p><p>解析<strong>允许</strong>字符串中含有非数字字符，解析按从左到右的顺序，如果遇到非数字字符就停止。而转换<strong>不允许</strong>出现非数字字符，否者会失败并返回NaN。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">'520'</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="string">'520px'</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">Number</span>(a); <span class="comment">// 520</span></span><br><span class="line"><span class="built_in">parseInt</span>(a); <span class="comment">// 520</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">Number</span>(b); <span class="comment">// NaN</span></span><br><span class="line"><span class="built_in">parseInt</span>(b); <span class="comment">// 520</span></span><br></pre></td></tr></table></figure><p><code>parseInt</code>方法第二个参数用于指定转换的基数，ES5默认为10进制。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">2</span>); <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">8</span>); <span class="comment">// 8</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">10</span>); <span class="comment">// 10</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">16</span>);  <span class="comment">// 16</span></span><br></pre></td></tr></table></figure><p>对于网上<code>parseInt(0.0000008)</code>的结果为什么为8，原因在于0.0000008转换成字符为&quot;8e-7&quot;，然后根据<code>parseInt</code>的解析规则自然得到&quot;8&quot;这个结果。</p><h4> <span id="拼接操作x-or-stringx"><code>+</code>拼接操作，<code>+x</code> or <code>String(x)</code>？</span></h4><p>+运算符可用于数字加法，同时也可以用于字符串拼接。如果+的其中一个操作符是字符串(或者通过 隐式强制转换可以得到字符串)，则执行字符串拼接；否者执行数字加法。</p><p>需要注意的时对于数组而言，不能通过<code>valueOf()</code>方法得到简单基本类型值，于是转而调用<code>toString()</code>方法。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>,<span class="number">2</span>] + [<span class="number">3</span>, <span class="number">4</span>]; <span class="comment">// "1,23,4"</span></span><br></pre></td></tr></table></figure><p>对于对象同样会先调用<code>valueOf()</code>方法，然后通过<code>toString()</code>方法返回对象的字符串表示。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = &#123;&#125;;</span><br><span class="line">a + <span class="number">123</span>; <span class="comment">// "[object Object]123"</span></span><br></pre></td></tr></table></figure><p>对于<code>a + &quot;&quot;</code>隐式转换和<code>String(a)</code>显示转换有一个细微的差别：<code>a + ''</code>会对a调用<code>valueOf()</code>方法，而<code>String()</code>直接调用<code>toString()</code>方法。大多数情况下我们不会考虑这个问题，除非真遇到。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a  = &#123;</span><br><span class="line">  valueOf: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="number">42</span>; &#125;,</span><br><span class="line">  toString: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="number">4</span>; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">a + <span class="string">''</span>; <span class="comment">// 42</span></span><br><span class="line"><span class="built_in">String</span>(a); <span class="comment">// 4</span></span><br></pre></td></tr></table></figure><h4> <span id="判断对象的实例">判断对象的实例</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一: ES3</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!(<span class="keyword">this</span> <span class="keyword">instanceof</span> Person)) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Person(name, age);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">  <span class="keyword">this</span>.age = age;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二: ES5</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> self = <span class="keyword">this</span> <span class="keyword">instanceof</span> Person ? <span class="keyword">this</span> : <span class="built_in">Object</span>.create(Person.prototype);</span><br><span class="line">  self.name = name;</span><br><span class="line">  self.age = age;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> self;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三：ES6</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="keyword">new</span>.target) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="string">'Peron must called with new'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">  <span class="keyword">this</span>.age = age;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="数据安全类型检查">数据安全类型检查</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 对象</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isObject</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Object</span>.prototype.toString.call(value).slice(<span class="number">8</span>, <span class="number">-1</span>) === <span class="string">'Object'</span><span class="string">';</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 数组</span></span><br><span class="line"><span class="string">function isArray(value) &#123;</span></span><br><span class="line"><span class="string">  return Object.prototype.toString.call(value).slice(8, -1) === '</span><span class="built_in">Array</span><span class="string">';</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 函数</span></span><br><span class="line"><span class="string">function isFunction(value) &#123;</span></span><br><span class="line"><span class="string">  return Object.prototype.toString.call(value).slice(8, -1) === '</span><span class="built_in">Function</span><span class="string">';</span></span><br><span class="line"><span class="string">&#125;</span></span><br></pre></td></tr></table></figure><h4> <span id="让数字的字面值看起来像对象">让数字的字面值看起来像对象</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">2.</span>toString(); <span class="comment">// Uncaught SyntaxError: Invalid or unexpected token</span></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>.toString(); <span class="comment">// 第二个点号可以正常解析</span></span><br><span class="line"><span class="number">2</span> .toString(); <span class="comment">// 注意点号前面的空格</span></span><br><span class="line">(<span class="number">2</span>).toString(); <span class="comment">// 2先被计算</span></span><br></pre></td></tr></table></figure><h4> <span id="对象可计算属性名仅在es6中">对象可计算属性名(仅在ES6中)</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> suffix = <span class="string">' name'</span>;</span><br><span class="line"><span class="keyword">var</span> person = &#123;</span><br><span class="line">  [<span class="string">'first'</span> + suffix]: <span class="string">'Nicholas'</span>,</span><br><span class="line">  [<span class="string">'last'</span> + suffix]: <span class="string">'Zakas'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">person[<span class="string">'first name'</span>]; <span class="comment">// "Nicholas"</span></span><br><span class="line">person[<span class="string">'last name'</span>]; <span class="comment">// "Zakas"</span></span><br></pre></td></tr></table></figure><h4> <span id="数字四舍五入">数字四舍五入</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// v: 值，p: 精度</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> (<span class="params">v, p</span>) </span>&#123;</span><br><span class="line">  p = <span class="built_in">Math</span>.pow(<span class="number">10</span>, p &gt;&gt;&gt; <span class="number">31</span> ? <span class="number">0</span> : p | <span class="number">0</span>)</span><br><span class="line">  v *= p;</span><br><span class="line">  <span class="keyword">return</span> (v + <span class="number">0.5</span> + (v &gt;&gt; <span class="number">31</span>) | <span class="number">0</span>) / p</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">round(<span class="number">123.45353</span>, <span class="number">2</span>); <span class="comment">// 123.45</span></span><br></pre></td></tr></table></figure><h4> <span id="在浏览器中根据url下载文件">在浏览器中根据url下载文件</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">download</span>(<span class="params">url</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> isChrome = navigator.userAgent.toLowerCase().indexOf(<span class="string">'chrome'</span>) &gt; <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">var</span> isSafari = navigator.userAgent.toLowerCase().indexOf(<span class="string">'safari'</span>) &gt; <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (isChrome || isSafari) &#123;</span><br><span class="line">    <span class="keyword">var</span> link = <span class="built_in">document</span>.createElement(<span class="string">'a'</span>);</span><br><span class="line">    link.href = url;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (link.download !== <span class="literal">undefined</span>) &#123;</span><br><span class="line">      <span class="keyword">var</span> fileName = url.substring(url.lastIndexOf(<span class="string">'/'</span>) + <span class="number">1</span>, url.length);</span><br><span class="line">      link.download = fileName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">document</span>.createEvent) &#123;</span><br><span class="line">      <span class="keyword">var</span> e = <span class="built_in">document</span>.createEvent(<span class="string">'MouseEvents'</span>);</span><br><span class="line">      e.initEvent(<span class="string">'click'</span>, <span class="literal">true</span>, <span class="literal">true</span>);</span><br><span class="line">      link.dispatchEvent(e);</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (url.indexOf(<span class="string">'?'</span>) === <span class="number">-1</span>) &#123;</span><br><span class="line">    url += <span class="string">'?download'</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">window</span>.open(url, <span class="string">'_self'</span>);</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="快速生成uuid">快速生成UUID</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">uuid</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> d = <span class="keyword">new</span> <span class="built_in">Date</span>().getTime();</span><br><span class="line">  <span class="keyword">var</span> uuid = <span class="string">'xxxxxxxxxxxx-4xxx-yxxx-xxxxxxxxxxxx'</span>.replace(<span class="regexp">/[xy]/g</span>, <span class="function"><span class="keyword">function</span>(<span class="params">c</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> r = (d + <span class="built_in">Math</span>.random() * <span class="number">16</span>) % <span class="number">16</span> | <span class="number">0</span>;</span><br><span class="line">    d = <span class="built_in">Math</span>.floor(d / <span class="number">16</span>);</span><br><span class="line">    <span class="keyword">return</span> (c == <span class="string">'x'</span> ? r : (r &amp; <span class="number">0x3</span> | <span class="number">0x8</span>)).toString(<span class="number">16</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> uuid;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">uuid(); <span class="comment">// "33f7f26656cb-499b-b73e-89a921a59ba6"</span></span><br></pre></td></tr></table></figure><h4> <span id="javascript浮点数精度问题">JavaScript浮点数精度问题</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isEqual</span>(<span class="params">n1, n2, epsilon</span>) </span>&#123;</span><br><span class="line">  epsilon = epsilon == <span class="literal">undefined</span> ? <span class="number">10</span> : epsilon; <span class="comment">// 默认精度为10</span></span><br><span class="line">  <span class="keyword">return</span> n1.toFixed(epsilon) === n2.toFixed(epsilon);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">0.1</span> + <span class="number">0.2</span>; <span class="comment">// 0.30000000000000004</span></span><br><span class="line">isEqual(<span class="number">0.1</span> + <span class="number">0.2</span>, <span class="number">0.3</span>); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="number">0.7</span> + <span class="number">0.1</span> + <span class="number">99.1</span> + <span class="number">0.1</span>; <span class="comment">// 99.99999999999999</span></span><br><span class="line">isEqual(<span class="number">0.7</span> + <span class="number">0.1</span> + <span class="number">99.1</span> + <span class="number">0.1</span>, <span class="number">100</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure><h4> <span id="格式化表单数据">格式化表单数据</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatParam</span>(<span class="params">obj</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> query = <span class="string">''</span>, name, value, fullSubName, subName, subValue, innerObj, i;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span>(name <span class="keyword">in</span> obj) &#123;</span><br><span class="line">    value = obj[name];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(value <span class="keyword">instanceof</span> <span class="built_in">Array</span>) &#123;</span><br><span class="line">      <span class="keyword">for</span>(i=<span class="number">0</span>; i&lt;value.length; ++i) &#123;</span><br><span class="line">        subValue = value[i];</span><br><span class="line">        fullSubName = name + <span class="string">'['</span> + i + <span class="string">']'</span>;</span><br><span class="line">        innerObj = &#123;&#125;;</span><br><span class="line">        innerObj[fullSubName] = subValue;</span><br><span class="line">        query += formatParam(innerObj) + <span class="string">'&amp;'</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span>(value <span class="keyword">instanceof</span> <span class="built_in">Object</span>) &#123;</span><br><span class="line">      <span class="keyword">for</span>(subName <span class="keyword">in</span> value) &#123;</span><br><span class="line">        subValue = value[subName];</span><br><span class="line">        fullSubName = name + <span class="string">'['</span> + subName + <span class="string">']'</span>;</span><br><span class="line">        innerObj = &#123;&#125;;</span><br><span class="line">        innerObj[fullSubName] = subValue;</span><br><span class="line">        query += formatParam(innerObj) + <span class="string">'&amp;'</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span>(value !== <span class="literal">undefined</span> &amp;&amp; value !== <span class="literal">null</span>)</span><br><span class="line">      query += <span class="built_in">encodeURIComponent</span>(name) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(value) + <span class="string">'&amp;'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> query.length ? query.substr(<span class="number">0</span>, query.length - <span class="number">1</span>) : query;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> param = &#123;</span><br><span class="line">  name: <span class="string">'jenemy'</span>,</span><br><span class="line">  likes: [<span class="number">0</span>, <span class="number">1</span>, <span class="number">3</span>],</span><br><span class="line">  memberCard: [</span><br><span class="line">    &#123; <span class="attr">title</span>: <span class="string">'1'</span>, <span class="attr">id</span>: <span class="number">1</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">title</span>: <span class="string">'2'</span>, <span class="attr">id</span>: <span class="number">2</span> &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">formatParam(param); <span class="comment">// "name=12&amp;likes%5B0%5D=0&amp;likes%5B1%5D=1&amp;likes%5B2%5D=3&amp;memberCard%5B0%5D%5Btitle%5D=1&amp;memberCard%5B0%5D%5Bid%5D=1&amp;memberCard%5B1%5D%5Btitle%5D=2&amp;memberCard%5B1%5D%5Bid%5D=2"</span></span><br></pre></td></tr></table></figure><h4> <span id="创建指定长度非空数组">创建指定长度非空数组</span></h4><p>在JavaScript中可以通过<code>new Array(3)</code>的形式创建一个长度为3的空数组。在老的Chrome中其值为[undefined x 3]，在最新的Chrome中为[empty x 3]，即空单元数组。在老Chrome中，相当于显示使用<code>[undefined, undefined, undefined]</code>的方式创建长度为3的数组。</p><p>但是，两者在调用<code>map()</code>方法的结果是明显不同的</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>);</span><br><span class="line"><span class="keyword">var</span> b = [<span class="literal">undefined</span>, <span class="literal">undefined</span>, <span class="literal">undefined</span>];</span><br><span class="line"></span><br><span class="line">a.map(<span class="function">(<span class="params">v, i</span>) =&gt;</span> i); <span class="comment">// [empty × 3]</span></span><br><span class="line">b.map(<span class="function">(<span class="params">v, i</span>) =&gt;</span> i); <span class="comment">// [0, 1, 2]</span></span><br></pre></td></tr></table></figure><p>多数情况我们期望创建的是包含<code>undefined</code>值的指定长度的空数组，可以通过下面这种方法来达到目的：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="built_in">Array</span>.apply(<span class="literal">null</span>, &#123; <span class="attr">length</span>: <span class="number">3</span> &#125;);</span><br><span class="line"></span><br><span class="line">a; <span class="comment">// [undefined, undefined, undefined]</span></span><br><span class="line">a.map(<span class="function">(<span class="params">v, i</span>) =&gt;</span> i); <span class="comment">// [0, 1, 2]</span></span><br></pre></td></tr></table></figure><p>总之，尽量不要创建和使用空单元数组。</p><h4> <span id="debounce方法">debounce方法</span></h4><p><code>debounce()</code>方法用来延迟执行函数。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> debounce = <span class="function"><span class="keyword">function</span> (<span class="params">func, threshold, execAsap</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> timeout;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">debounced</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> obj = <span class="keyword">this</span>, args = <span class="built_in">arguments</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">delayed</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (!execAsap)</span><br><span class="line">        func.apply(obj, args);</span><br><span class="line">      timeout = <span class="literal">null</span>;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (timeout)</span><br><span class="line">      clearTimeout(timeout);</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (execAsap)</span><br><span class="line">      func.apply(obj, args);</span><br><span class="line"></span><br><span class="line">    timeout = setTimeout(delayed, threshold || <span class="number">100</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4> <span id="判断客户端">判断客户端</span></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> browser = &#123;</span><br><span class="line">    v: (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> u = navigator.userAgent,</span><br><span class="line">            app = navigator.appVersion,</span><br><span class="line">            p = navigator.platform;</span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            trident: u.indexOf(<span class="string">'Trident'</span>) &gt; <span class="number">-1</span>, <span class="comment">//IE内核</span></span><br><span class="line">            presto: u.indexOf(<span class="string">'Presto'</span>) &gt; <span class="number">-1</span>, <span class="comment">//opera内核</span></span><br><span class="line">            webKit: u.indexOf(<span class="string">'AppleWebKit'</span>) &gt; <span class="number">-1</span>, <span class="comment">//苹果、谷歌内核</span></span><br><span class="line">            gecko: u.indexOf(<span class="string">'Gecko'</span>) &gt; <span class="number">-1</span> &amp;&amp; u.indexOf(<span class="string">'KHTML'</span>) == <span class="number">-1</span>, <span class="comment">//火狐内核</span></span><br><span class="line">            mobile: !!u.match(<span class="regexp">/AppleWebKit.*Mobile.*/</span>), <span class="comment">//是否为移动终端</span></span><br><span class="line">            ios: !!u.match(<span class="regexp">/i[^;]+;( U;)? CPU.+Mac OS X/</span>), <span class="comment">//ios终端</span></span><br><span class="line">            android: u.indexOf(<span class="string">'Android'</span>) &gt; <span class="number">-1</span> || u.indexOf(<span class="string">'Linux'</span>) &gt; <span class="number">-1</span>, <span class="comment">//android终端或uc浏览器</span></span><br><span class="line">            iPhone: u.indexOf(<span class="string">'iPhone'</span>) &gt; <span class="number">-1</span>, <span class="comment">//是否为iPhone或者QQHD浏览器</span></span><br><span class="line">            iPad: u.indexOf(<span class="string">'iPad'</span>) &gt; <span class="number">-1</span>, <span class="comment">//是否iPad</span></span><br><span class="line">            weixin: u.indexOf(<span class="string">'MicroMessenger'</span>) &gt; <span class="number">-1</span>, <span class="comment">//是否微信</span></span><br><span class="line">            webApp: u.indexOf(<span class="string">'Safari'</span>) == <span class="number">-1</span>, <span class="comment">//是否web应该程序，没有头部与底部</span></span><br><span class="line">            UCB: u.match(<span class="regexp">/UCBrowser/i</span>) == <span class="string">"UCBrowser"</span>,</span><br><span class="line">            QQB: u.match(<span class="regexp">/MQQBrowser/i</span>) == <span class="string">"MQQBrowser"</span>,</span><br><span class="line">            win: p.indexOf(<span class="string">'Win'</span>) &gt; <span class="number">-1</span>, <span class="comment">//判断是否是WIN操作系统</span></span><br><span class="line">            mac: p.indexOf(<span class="string">'Mac'</span>) &gt; <span class="number">-1</span> <span class="comment">//判断是否是Mac操作系统</span></span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;)()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><hr><ul class="pager"><li class="previous"> <a href="/hux/2018/08/26/Markdown使用指南/" data-toggle="tooltip" data-placement="top" title="Markdown使用指南">&larr; Previous Post</a></li><li class="next"> <a href="/hux/2018/08/18/用图标和示例解释Await和Async/" data-toggle="tooltip" data-placement="top" title="用图标和示例解释Await和Async">Next Post &rarr;</a></li></ul><div class="comment"><div id="disqus_thread" class="disqus-thread"></div></div></div><div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 sidebar-container"><section><h5><a href="/hux/tags/">FEATURED TAGS</a></h5><div class="tags"></div></section><hr><h5>FRIENDS</h5><ul class="list-inline"><li><a href="https://csjiabin.github.io" target="_blank">CSjiabin&#39;s Blog</a></li><li><a href="http://zhengwuyang.com" target="_blank">WY</a></li><li><a href="https://www.jianshu.com/u/f7f87e65552a" target="_blank">简书·csjiabin</a></li></ul></div></div></div></article><script type="text/javascript">var disqus_shortname="csjiabin",disqus_identifier="https://csjiabin.github.io/2018/08/22/JavaScript有用的代码片段和trick/",disqus_url="https://csjiabin.github.io/2018/08/22/JavaScript有用的代码片段和trick/";!function(){var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src="//"+disqus_shortname+".disqus.com/embed.js",(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).appendChild(t)}()</script><script>function async(e,n){var t=document,a="script",r=t.createElement(a),c=t.getElementsByTagName(a)[0];r.src=e,n&&r.addEventListener("load",function(e){n(null,e)},!1),c.parentNode.insertBefore(r,c)}</script><script>async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){anchors.options={visible:"always",placement:"right",icon:"#"},anchors.add().remove(".intro-header h1").remove(".subheading").remove(".sidebar-container h5")})</script><style>@media all and (min-width:800px){.anchorjs-link{position:absolute;left:-.75em;font-size:1.1em;margin-top:-.1em}}</style><footer><div class="container"><div class="row"><div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"><ul class="list-inline text-center"><li><a target="_blank" href="https://www.jianshu.com/u/f7f87e65552a"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-stack-1x fa-inverse">简</i></span></a></li><li><a target="_blank" href="https://www.zhihu.com/people/csjiabin"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-stack-1x fa-inverse">知</i></span></a></li><li><a target="_blank" href="https://github.com/csjiabin"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-github fa-stack-1x fa-inverse"></i></span></a></li></ul><p class="copyright text-muted"> Copyright &copy; CSjiabin&#39;s Blog 2018<br> Theme by <a href="http://huangxuan.me">Hux</a><span style="display:inline-block;margin:0 5px"><i class="fa fa-heart"></i></span> Ported by <a href="https://csjiabin.github.io">CSjiabin</a> |<iframe style="margin-left:2px;margin-bottom:-5px" frameborder="0" scrolling="0" width="91px" height="20px" src="https://ghbtns.com/github-btn.html?user=csjiabin&repo=csjiabin.github.io&type=star&count=true"></iframe></p></div></div></div></footer><script src="/hux/js/jquery.min.js"></script><script src="/hux/js/bootstrap.min.js"></script><script src="/hux/js/hux-blog.min.js"></script><script type="text/javascript">
        if(navigator.serviceWorker){
            // For security reasons, a service worker can only control the pages that are in the same directory level or below it. That's why we put sw.js at ROOT level.
            navigator.serviceWorker
                .register('/hux/sw.js')
                .then((registration) => {console.log('Service Worker Registered. ', registration)})
                .catch((error) => {console.log('ServiceWorker registration failed: ', error)})
        }
    </script><script>function async(e,n){var t=document,a="script",r=t.createElement(a),c=t.getElementsByTagName(a)[0];r.src=e,n&&r.addEventListener("load",function(e){n(null,e)},!1),c.parentNode.insertBefore(r,c)}</script><script>0!==$("#tag_cloud").length&&async("/hux/js/jquery.tagcloud.js",function(){$.fn.tagcloud.defaults={color:{start:"#bbbbee",end:"#0085a1"}},$("#tag_cloud a").tagcloud()})</script><script>async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js",function(){var c=document.querySelector("nav");c&&FastClick.attach(c)})</script><script>var _gaId="UA-124238838-1",_gaDomain="csjiabin.github.io";!function(a,e,g,n,t,i,c){a.GoogleAnalyticsObject="ga",a.ga=a.ga||function(){(a.ga.q=a.ga.q||[]).push(arguments)},a.ga.l=1*new Date,i=e.createElement(g),c=e.getElementsByTagName(g)[0],i.async=1,i.src="//www.google-analytics.com/analytics.js",c.parentNode.insertBefore(i,c)}(window,document,"script"),ga("create",_gaId,_gaDomain),ga("send","pageview")</script><script async src="https://www.googletagmanager.com/gtag/js?UA-124238838-1"></script><script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","UA-124238838-1")</script><script>var _baId="2620e69674d25088f870bef114e8ff89",_hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="//hm.baidu.com/hm.js?"+_baId;var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()</script><script src="https://c.mipcdn.com/static/v1/mip.js"></script><script>!function(){var t=document.createElement("script"),e=window.location.protocol.split(":")[0];t.src="https"===e?"https://zz.bdstatic.com/linksubmit/push.js":"http://push.zhanzhang.baidu.com/push.js";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}()</script><a id="rocket" href="#top" class=""></a><script type="text/javascript" src="/hux/js/totop.js?v=1.0.0" async=""></script><script type="text/javascript" src="/hux/js/toc.js?v=1.0.0" async=""></script> <img src="/hux/img/apple-touch-icon.png" width="0" height="0"></body></html>